package platformlog_logic

import (
	"context"
	"fmt"
	"yunzhan/common/models"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryLogsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewQueryLogsLogic 查询部署日志
func NewQueryLogsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryLogsLogic {
	return &QueryLogsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QueryLogsLogic) QueryLogs(req *types.QueryLogsRequest) (resp *types.QueryLogsResponse, err error) {
	flag := l.svcCtx.Config.UseMysql

	var selectSQL string
	selectSQL = fmt.Sprintf(`
		SELECT task_id, node_host, component, component_role, step_number, message, log_level, created_at
		FROM deployment_logs
		WHERE cluster_id = %s`, req.ClusterID)

	if flag {
		selectSQL = fmt.Sprintf(`
		SELECT task_id, node_host, component, component_role, step_number, message, log_level, created_at
		FROM yunfan_bigdata.deployment_logs
		WHERE cluster_id = %s`, req.ClusterID)
	}

	// 构建查询条件
	var params []interface{}
	if req.TaskID != "" {
		selectSQL += " AND task_id = ?"
		params = append(params, req.TaskID)
	}
	if req.Component != "" {
		selectSQL += " AND component = ?"
		params = append(params, req.Component)
	}
	if req.ComponentRole != "" {
		selectSQL += " AND component_role = ?"
		params = append(params, req.ComponentRole)
	}
	if req.LogLevel != "" {
		selectSQL += " AND log_level = ?"
		params = append(params, req.LogLevel)
	}
	if req.CreatedTime != "" {
		selectSQL += " AND created_at >= ?"
		params = append(params, req.CreatedTime)
	}

	selectSQL += " ORDER BY created_at DESC"

	var logs []models.LogEntry
	err = l.svcCtx.Conn.QueryRows(&logs, selectSQL, params...)
	if err != nil {
		logx.Errorf("failed to query logs: %v", err)
		return nil, err
	}

	return &types.QueryLogsResponse{
		Code:    200,
		Message: "查询日志成功",
		Data:    logs}, nil
}
